package com.blog.controller;

import com.blog.entity.User;
import com.blog.service.UserService;
import com.blog.util.JwtUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AuthController {

    private final AuthenticationManager authenticationManager;
    private final JwtUtil jwtUtil;
    private final UserService userService;

    public AuthController(AuthenticationManager authenticationManager,
                         JwtUtil jwtUtil,
                         UserService userService) {
        this.authenticationManager = authenticationManager;
        this.jwtUtil = jwtUtil;
        this.userService = userService;
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        try {
            System.out.println("收到登录请求: " + loginRequest);
            
            String username = loginRequest.get("username");
            String password = loginRequest.get("password");
            
            if (username == null || password == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户名和密码不能为空");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            System.out.println("尝试认证用户: " + username);

            Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, password)
            );

            SecurityContextHolder.getContext().setAuthentication(authentication);
            Object principal = authentication.getPrincipal();
            String jwt;
            if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
                jwt = jwtUtil.generateToken((org.springframework.security.core.userdetails.UserDetails) principal);
            } else {
                throw new RuntimeException("登录异常：用户信息类型不匹配");
            }

            Map<String, Object> response = new HashMap<>();
            response.put("token", jwt);
            response.put("username", username);
            User user = userService.findByUsername(username);
            response.put("role", user.getRole());
            
            System.out.println("登录成功: " + username);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            System.err.println("登录失败: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "登录失败: " + e.getMessage());
            return ResponseEntity.status(401).body(errorResponse);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        User registeredUser = userService.register(user);
        return ResponseEntity.ok(registeredUser);
    }
} 